package cn.edu.zjgsu.handler;

import cn.edu.zjgsu.template.ResultBean;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.util.JSONPObject;
import lombok.Cleanup;
import org.apache.shiro.authz.UnauthenticatedException;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author: mwq
 * DateTime: 2017/11/12 13:34
 * Description:
 */
public class ExceptionHandler implements HandlerExceptionResolver
{
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
    {
        ModelAndView mv = new ModelAndView();
        if(ex instanceof UnauthenticatedException)
        {
            mv.addObject("code", 500);
            response.setContentType("application/json");
            try
            {
                @Cleanup  PrintWriter pw = response.getWriter();
                ResultBean resultBean = new ResultBean();
                resultBean.setCode(403);
                pw.write(JSONObject.toJSONString(resultBean));
            } catch (IOException e)
            {
                e.printStackTrace();
            }

        }
        mv.setView(new RedirectView("/views/nopermission.html"));
        return null;
    }
}
